<template>
  <div>
    <ValidationProvider name="户籍地址" rules="required" v-slot="{ errors }">
      <van-field
        readonly
        clickable
        label="户籍地址"
        :value="label"
        placeholder="请选择户籍地址"
        @click="showAddressPicker = true"
        :error-message="errors[0]"
      />
    </ValidationProvider>

    <!-- 省市县picker -->
    <van-popup v-model="showAddressPicker" position="bottom" get-container="body">
      <van-area
        ref="area"
        :value="areaVal"
        :area-list="areaList"
        @confirm="onConfirmAddress"
        @cancel="showAddressPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { ValidationProvider, extend } from "vee-validate";
import { required } from "vee-validate/dist/rules";
import zh from "vee-validate/dist/locale/zh_CN";
import { getArea, selectArea } from "@/api/user.js";
import Bus from "@/views/userInfo/components/bus";

extend("required", {
  ...required,
  message: zh.messages["required"]
});
export default {
  data() {
    return {
      areaVal: this.value ? `${this.value[2]}` : '',
      areaList: {},
      showAddressPicker: false,
    };
  },
  props: {
    value: {}
  },
  computed: {
    label() {
      let province, city, county, value;
      if (this.value) {
        value = `${this.value[2]}`;
      } else {
        value = "";
      }

      if (this.areaList.province_list) {
        province = this.areaList.province_list[`${value.substr(0, 2)}0000`];
      }
      if (this.areaList.city_list) {
        city = this.areaList.city_list[`${value.substr(0, 4)}00`];
      }
      if (this.areaList.county_list) {
        county = this.areaList.county_list[value];
      }
      return province && city && county ? `${province}-${city}-${county}` : "";
    },
  },
  created() {
    // 获取省市区数据
    selectArea().then(({ data }) => {
      this.areaList = {
        province_list: data[0],
        city_list: data[1],
        county_list: data[2]
      };
    }).then(res => {
        Bus.$emit("areaChange",this.value ? this.value[2] : '');
    })
  },
  methods: {
    onConfirmAddress(obj) {
      this.showAddressPicker = false;

      this.$emit("input", obj.map(m => m.code));

      Bus.$emit("areaChange", obj[2].code);
    }
  },
  components: {
    ValidationProvider
  }
};
</script>

<style lang='scss'>
</style>
